<?php
require_once('base_controller.php');

class publication_controller extends base_controller
{
    
    public function dowork()
    {
        $msg_response = new message(WARNING_query_failed, 0, STR_text);
        
        try {
            switch ($this->method)
            {
                case 'publish':
                    {      
                        $iduser = $this->current_id;
                        $text = addslashes(trim($this->parameters['text']));
                        $pics = empty($_FILES["img"]) ? null : $_FILES["img"];
                        
                        $succeed = self::publish($iduser, $text, $pics);
                        
                        $msg_response = new message($succeed, 1, STR_number);
                    }
                    break;
                    
                case 'getallpubs':    //获取
                    {
                        $iduser = $this->current_id;
                        
                        $results = self::get_publications_all($iduser, false);
                        
                        $msg_response = new message($results, 1, STR_object);
                        
                    }
                    break;
                    
                case 'getpersonalpubs':    //获取
                        {
                            if(!isset($this->parameters['idtovisit']))
                                throw new Exception(warning_parameter_needed('idtovisit')); //                            
                            
                            $iduser = $this->current_id;
                            $idtovisit = $this->parameters['idtovisit'];
                    
                            $results = self::get_publications_personal($iduser, $idtovisit, false);
                    
                            $msg_response = new message($results, 1, STR_object);
                    
                        }
                        break;
                    
                case 'getpubs':
                    {
                        
                    }
                    break;
                    

                case 'getimg':
                    {
                        if(!isset($this->parameters['idpub']))
                            throw new Exception(warning_parameter_needed('idpub')); //
                        if(!isset($this->parameters['index']))
                            throw new Exception(warning_parameter_needed('index')); //
                        
                        $iduser = $this->current_id;
                        $idpub = $this->parameters['idpub'];
                        $indexpic = $this->parameters['index'];
                        
                        $results = self::get_img_by_idpub($idpub, $indexpic);
                                        
                        $msg_response = new message($results, 1, STR_number);
                    }
                    break;
                case '3':
                    {
                
                    }
                    break;
                
                    
                default:
                    {
                        
                    }
                    break;
            }
        } catch (Exception $e) {
            $msg_response->content = $e->getMessage();            
        }
        
        return $msg_response;       
    }
    
    
    /**
     * 
     * 此处用到了“事务 transaction”
     * @param unknown $iduser
     * @param unknown $text
     * @param unknown $pics
     * @return  
     */
    public static function publish($iduser, $text, $pics)
    {
        $db = db_connect();
        
        $numpics = (!empty($pics) && is_array($pics) && !empty($pics['name']))? count($pics['name']) : 0;        
        $time = datetime_now();
        
        $db->begin_transaction();
        
        $str_query = "insert into publications (iduser, time, text, numpics) values('".$iduser."', '".$time."', '".$text."', '".$numpics."');";
        
        $result = $db->query($str_query);
        
        db_is_result_succeed($result, $db);
        
        $idpub = $db->insert_id;
                
        if(!empty($pics) && is_array($pics) && !empty($pics['name']))
        {   
            for($p=0; $p < $numpics; $p++)
            {
                $tmp_name = ($pics['tmp_name'][$p]);
                $name = addslashes($pics['name'][$p]);
                $type = addslashes($pics['type'][$p]);
                
                $idpic = hash_file(STR_algo_hash_pic, $tmp_name);
                $ext = pathinfo($name, PATHINFO_EXTENSION);
                $path_save = PATH_upfiles.$idpic.($ext === '' ? '' : '.'.$ext);
                                
                //使用 iconv($in_charset, $out_charset, $str) 函数解决保存上传文件时文件名乱码的问题； 
                //windows系统下的中文默认编码格式为gb2312
                move_uploaded_file($tmp_name, iconv('utf-8', 'gb2312', $path_save));
                
                $str_query = "insert into pictures (idpic, idpub, name, type, ext, number) values ('".$idpic."','".$idpub."','".$name."','".$type."','".$ext."','".$p."');";
                
                $result = $db->query($str_query);
                
                if(!$result)
                {
                    $error = $db->error;
                    $db->rollback();
                    throw new Exception(WARNING_query_failed.": ".$error);
                }
            }
            
        }        
        
        $db->commit();
        
        $pub_new = array(
            "idpub" => $idpub,
            "iduser" => $iduser,
            "time" => $time,
            "text" => $text,
            "numpics" => $numpics
        );
        
        return $pub_new;
    }
    
    /**
     * 
     * @param unknown $iduser
     * @param unknown $start 从第几行开始，行数从1从始
     * @param unknown $numtoget
     */
    public static function get_publications($iduser, $start, $numtoget)
    {
        $db = db_connect();
        
        if(!is_numeric($start) || $start < 1 || !is_numeric($numtoget) || $numtoget < 1)
            throw new Exception("parameter \$start and \$numtoget should be numeric and larger than 1");
        
        $str_query = "select * from publications  limit ".($start - 1).", ".$numtoget.";";
            "select * from publications where iduser in ("
            ." select userask as id from friendship where useraccept = '".$iduser."' union select useraccept as id from friendship where userask = '".$iduser."' "
            .") limit ".($start - 1).", ".$numtoget.";";
        
        $result = $db->query($str_query);
        
        db_is_result_succeed($result, $db);
        
        $result = $result->fetch_object();
        
        return $result;
    }
    
    /**
     * 获取所有好友（另包括自己）的图文发表信息
     * @param unknown $iduser
     * @param unknown $isTimeAscending  是否按时间升序排列，如果为true，则升序，空或否其它情况为false
     * @return Ambigous <NULL, unknown>
     */
    public static function get_publications_all($iduser, $isTimeAscending)
    {
        $db = db_connect();
        
        $str_AscOrDesc = $isTimeAscending === true ? "asc" : "desc";
        $str_query = 
            "select publications.*, users.nickname as usernickname from publications, users where iduser in ("
            //所有好友及自己的id集合
            ." select userask as id from friendship where useraccept = '".$iduser."' union select useraccept as id from friendship where userask = '".$iduser."' "
            ."union select '".$iduser."' "
            .")"
            ." and users.id = publications.iduser order by time ".$str_AscOrDesc.";";
    
        $result = $db->query($str_query);
    
        db_is_result_succeed($result, $db);
    
        $result = dbresult_to_objects_array($result);
    
        return $result;
    }
    
    public static function get_publications_personal($iduser, $idtovisit, $isTimeAscending)
    {
        $db = db_connect();
        
        $str_AscOrDesc = $isTimeAscending === true ? "asc" : "desc";
        $str_query =
        "select publications.*, users.nickname as usernickname from publications, users where iduser = '".$idtovisit."' "
                    ." and users.id = '".$idtovisit."' order by time ".$str_AscOrDesc.";";
        
        $result = $db->query($str_query);
        
        db_is_result_succeed($result, $db);
        
        $result = dbresult_to_objects_array($result);
        
        return $result;
    }
    
    /**
     * 待再判断是否有权限获取（是否为好友关系等……）
     * @param unknown $idpub
     * @param unknown $index
     */
    public static function get_img_by_idpub($idpub, $index)
    {
        $db = db_connect();
        
        $str_query = "select idpic,name from pictures where idpub = '".$idpub."' and number = '".$index."';";
        
        $result = $db->query($str_query);
        
        db_is_result_succeed($result, $db);
        
        $result = $result->fetch_object();
        $ext = pathinfo($result->name, PATHINFO_EXTENSION);
        $path = PATH_upfiles.$result->idpic.($ext === '' ? '' : '.'.$ext);
        
        if(!file_exists(from_utf8_to_gb2312($path)))
        {
            header("HTTP/1.0 404 Not Found");
            exit;
        }
        else 
        {
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename='.$result->name);//basename($path)
            header('Content-Length: ' . filesize($path));
            readfile($path);
            exit;
        }
        
        //return $result;    
        
    }
    
    
}

?>